package humanMirror.controller.actions;

import humanMirror.model.controller.Controller;
import humanMirror.model.human.Human;
import humanMirror.model.questionLibrary.SqlWorker;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegisterAction implements Action {

    public String perform(HttpServletRequest request,
                          HttpServletResponse response) {

        String login = request.getParameter("login");
        String password = request.getParameter("password");
        Pattern p = Pattern.compile("[a-zA-Z0-9]+");
        Matcher loginMatcher = p.matcher(login);
        Matcher passwordMatcher = p.matcher(password);

        if (!loginMatcher.matches() || !passwordMatcher.matches()) {
            return showErrorPage(request, "forbiden symbols in login/password ");
        }

        try {
            if(SqlWorker.registerUser(login,password)){
                HttpSession session = request.getSession(true);
                session.setAttribute("user", login);
                session.setAttribute("controller", new Controller(new Human()));
                session.setAttribute("questionNumber", 0);
                return "/main.jsp";
            }
        } catch (Exception e) {
            return showErrorPage(request,e.getMessage());
        }
        return null;
    }//perform
    private String showErrorPage(HttpServletRequest request,String error){
        request.setAttribute("errorMessage", error);
        return "/error.jsp";
    }
}
